package cn.dota2info.elk.user.config;

import cn.dota2info.elk.entity.UserInfo;
import cn.dota2info.elk.user.utils.CacheUtil;
import cn.dota2info.elk.user.utils.JwtHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;


@Component
@Order(1)
public class RequestFilter implements WebFilter {

    @Value("${exclude-url}")
    private String excludedUrl;
    @Value("${base64Security}")
    private String base64Security;
    @Override
    //返回Mono<Void> 表示该过滤器的处理已经结束。
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

         /*ServerWebExchange寓意交换/兑换(exchange):用请求换回响应. 所以ServerWebExchange包含有成对的http请求对象ServerHttpRequest和http响应对象ServerHttpResponse.
         ServerHttpRequest是webflux controller中的http请求对象，类似webmvc中的HttpServletRequest*/
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String method =  request.getMethod().name();
        if (method.equals("OPTIONS")) {
            return chain.filter(exchange);
        }
        String url=request.getURI().getPath();
        if(isNotFilter(url)){
            return chain.filter(exchange);
        }

        //获取请求http头appKey值
        String token = request.getHeaders().getFirst("X-Token");
        if(token==null){
            response.setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return Mono.empty();
        }
        try {
            UserInfo userInfo=JwtHelper.getUserInfo(token,base64Security);
            CacheUtil.setValue("userInfo",userInfo);
        }catch (Exception e){
            e.printStackTrace();
            response.setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return Mono.empty();
        }
       /*过滤器链的概念都是类似的，调用过滤器链的filter方法将请求转到下一个filter，如果该filter是最后一  个filter,那就转到

       该请求对应的handler,也就是controller方法或函数式endpoint */

        return chain.filter(exchange);

    }

    private boolean isNotFilter(String path){
        String[] paths=excludedUrl.split(",");
        for(String p:paths){
            if(p.equals(path)){
                return true;
            }
        }
        return false;

    }
}







